#include <QApplication>

#include "net/server.h"
#include "net/client.h"
#include "config/configreader.h"
#include "config/applicationconfiguration.h"
#include "gui/mainwindow.h"

#define CONFIG_PATH "/home/maciej/Pulpit/config.xml"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // load app conf
    if(!ApplicationConfiguration::getInstance().loadConfig(CONFIG_PATH))
        exit(EXIT_FAILURE);

    MainWindow* mw = new MainWindow;

    // create server worker and new thread object
    Server *serverWorker = new Server;
    QThread *serverWorkerThread = new QThread;

    // run server when thread starts
    QObject::connect(serverWorkerThread, SIGNAL(started()), serverWorker, SLOT(run()));

    // set status label when server starts
    QObject::connect(serverWorker, SIGNAL(serverStarted(QString)), mw, SLOT(setServerStatus(QString)));

    // add client to list when he connected
    QObject::connect(serverWorker, SIGNAL(clientConnected(QString)), mw, SLOT(addClient(QString)));

    // remove client from list when he disconnected
    QObject::connect(serverWorker, SIGNAL(clientDisconnected(QString)), mw, SLOT(removeClient(QString)));

    serverWorker->moveToThread(serverWorkerThread);

    // start server thread
    serverWorkerThread->start();

    // create client worker and new thread object
    Client* clientWorker = new Client;
    QThread *clientWorkerThread = new QThread;

    // run client when thread starts
    QObject::connect(clientWorkerThread, SIGNAL(started()), clientWorker, SLOT(startPolling()));

    // add server to list when we successfully connected
    QObject::connect(clientWorker, SIGNAL(addServer(QString,int)), mw, SLOT(addServer(QString,int)));

    // remove server from list when server broke connection
    QObject::connect(clientWorker, SIGNAL(removeServer(QString)), mw, SLOT(removeServer(QString)));

    clientWorker->moveToThread(clientWorkerThread);

    // start server thread
    clientWorkerThread->start();

    mw->show();

    // enable logging messages in main window which were received by server
    QObject::connect(serverWorker, SIGNAL(logMsg(QString)), mw, SLOT(logMessage(QString)));

    //
    QObject::connect(mw, SIGNAL(broadcastMessage(QString)), clientWorker, SLOT(broadcastMessage(QString)));

    return a.exec();
}
